package com.admin.controller;


import com.admin.entity.Admin;
import com.admin.entity.Station;
import com.admin.service.IAdminService;
import com.admin.service.IStationService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bean.ResponseBean;
import com.token.JwtUtil;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * 站点模块控制层
 *
 * @author m
 * arisheng
 * @since 2019-11-15
 */
@RestController
@RequestMapping("/admin/station")
public class StationController {


    @Autowired
    private IStationService stationService;

    @Autowired
    private IAdminService iAdminService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private HttpServletRequest request;

    private static Logger logger = Logger.getLogger(String.valueOf(StationController.class));


    /**
     * 去修改设置遥控密码页面
     * @param ID
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/setYaokongPwd")
    public String setYaokongPwd(int ID,HttpServletResponse response) throws  Exception
    {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
           String str = "<script>alert('请登录先');</script>";
           return str;
        }

        request.setAttribute("ID", ID);

        Station station = stationService.getById(ID);
        request.setAttribute("station", station);
        request.getRequestDispatcher("/admin/station/setYaokongPassword.jsp").forward(request,response);
        return null ;
    }


    /**
     * 保存遥控密码
     * @param ID
     * @param password
     * @return
     */
    @RequestMapping("/saveYaokongPassword")
    public ResponseBean saveYaokongPassword(String ID,String password)
    {
         Station  station = stationService.getById(ID);
         if (station==null)
         {
             return new ResponseBean(500,"站点不存在",null);
         }
         station.setYaokongPwd(password);
         stationService.updateById(station);
         return new ResponseBean(200,"修改成功",null);
    }


    @RequestMapping(value = "/query/ZhanDianPeiZhi",method = RequestMethod.GET)
    public ResponseBean queryZhanDianPeiZhi(@RequestParam Integer stationId){

        String token = request.getHeader("token");

        Integer adminId = iAdminService.selectAdminId(stationId);

        int i = iAdminService.selectQuanxian(adminId, token);

        if(i==200){

            return new ResponseBean(200,"操作成功","");
        }

        return new ResponseBean(500,"操作失败","");
    }

    /**
     * 判断站点的token  和传过来的站点是否一致
     * @return
     */
    @RequestMapping(value = "/query/stationLoginQuanxXian",method = RequestMethod.GET)
    public ResponseBean queryStationQuanXian(@RequestParam Integer stationId){

        String token = request.getHeader("token");

        String stationId1 = JwtUtil.getStationId(token);

        int i = stationService.queryStationLoginUser(stationId, token);
        if(i==200){

            return new ResponseBean(200,"操作成功","");
        }

        return new ResponseBean(401, "没有登录", null);
    }

    @RequestMapping(value = "/query/StationLogin",method = RequestMethod.GET)
    public ResponseBean queryStationLogin(HttpServletRequest request, HttpServletResponse response, String username, String password){

        //从redis里取登录失败次数
        BoundValueOperations b = redisTemplate.boundValueOps(username);
        if ("-1".equals(b.get())) {
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试", null);
        }

        //查数据是否有这个用户
        Station station=stationService.queryStationLogin(username,password);

        if (station != null) {
            b.set("0");
            String token = JwtUtil.generToken(null, station.getStationId()+"", null);
            //响应头也存在跨域
            response.addHeader("Access-Control-Expose-Headers", "token");
            //发送给客户端
            response.addHeader("token", token);

            request.getSession().setAttribute("station", station);

            return new ResponseBean(200, "success", station);
        }

        if (!redisTemplate.hasKey(username)) {
            b.set("1");
            b.expire(60, TimeUnit.SECONDS);
            //登录失败次数小于十，次数加一
        } else if (Integer.parseInt(b.get().toString()) < 10) {
            int tmp = Integer.parseInt(b.get().toString());
            b.set(String.valueOf(++tmp));
            b.expire(60, TimeUnit.SECONDS);
            //大于十，参数为-1,并一分钟内禁止登录
        } else {
            b.set("-1");
            b.expire(60, TimeUnit.SECONDS);
            return new ResponseBean(500, "您的登录次数过多，请于" + b.getExpire().intValue() + "秒后再次尝试",null);
        }
        return new ResponseBean(500, "用户名或密码错误", null);
    }
    /**
     * 可以根据编号/名称/日期/查询所有的站点（分页）
     *
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @RequestMapping("/selectAllStation")
    public ResponseBean selectAllStation(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }

        if (admin.getAdminParent()!=null && admin.getAdminParent()==0) {

            IPage p = stationService.selectAllStation(page, limit, map);
            return new ResponseBean(0, p.getTotal(), p.getRecords());
        }
        else{
            IPage p = stationService.selectAllStation(page, limit, map,admin);
            return new ResponseBean(0, p.getTotal(), p.getRecords());
        }





    }

    /**
     * 分页查询可以删除的站点
     * @param page
     * @param limit
     * @param map
     * @return
     */
    @RequestMapping("/selectAllDelStation")
    public ResponseBean selectAllDelStation(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map map) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage p = stationService.selectAllDelStation(page, limit, map);
        return new ResponseBean(0, p.getTotal(), p.getRecords());
    }

    /**
     * 根据主键修改站点修改密码
     *
     * @param s
     * @return
     */
    @PostMapping("/editStationPsdById")
    public ResponseBean editStationById(Station s,String adminidnow) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        if (s == null) {
            return new ResponseBean(0, null, null);
        }
        boolean f = stationService.updateById(s);
        int code = f ? 200 : 500;
        return new ResponseBean(code, null, null);
    }

    /**
     * 根据主键删除并且修改上级的火币数量
     *adminidnow表示当前登录用户的令牌
     * @param station
     * @return
     */
    @PostMapping("/deleteById")
    public ResponseBean deleteById(Station station,String adminidnow) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        int n = stationService.deleteStation(station);
        int code = n > 0 ? 200 : 500;
        return new ResponseBean(code, null, null);
    }

    /**
     * 根据id查找站点的信息
     *
     * @param stationId
     * @return
     */
    @RequestMapping("/selectById")
    public ResponseBean selectById(int stationId) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        Station s = stationService.getById(stationId);
        int code = s == null ? 500 : 200;
        return new ResponseBean(code, 0, s);
    }

    /**
     * 根据站点编号查询站点详表
     *
     * @param map
     * @return
     */
    @GetMapping("/queryByIdstationdetails")
    public ResponseBean queryByIdstationdetails(@RequestParam Map map) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        String stationId = (String) map.get("stationId");

        if (stationId == null || stationId == "") {
            return new ResponseBean(500, "查询失败", "未获取到编号");
        }

        // 判断站点编号存在
        boolean byId = stationService.findById(Integer.parseInt(stationId));
        if (byId == false) {
            return new ResponseBean(500, "查询失败", "无用户无信息");
        }

        Map byIdStation = stationService.findByIdStation(map);
        return new ResponseBean(200, "success", byIdStation);
    }

    /**
     * 修改站点详表
     *
     * @param station
     * @return
     */
    @PutMapping("/updateByIdStation")
    public ResponseBean updateByIdStation(@Valid @RequestBody Station station, BindingResult result) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        if (result.hasErrors()) {
            return new ResponseBean(500, "操作失败", result.getFieldError().getDefaultMessage());
        }
        // 判断站点Id存在
        boolean byId = stationService.findById(station.getStationId());
        if (byId == false) {
            return new ResponseBean(500, "操作失败", "请输入正确的修改条件");
        }

        boolean f = stationService.updateById(station);

        return ResponseBean.vo(f, 0);
    }

    /**
     * 计费管理火币充值_搜索框,模糊查询,分页
     *
     * @param page  layui分页参数
     * @param limit 分页参数
     * @param map   查询数据
     * @return
     */
    @RequestMapping("/jifei/querywocoinC")
    public ResponseBean querywocoinC(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map<String, Integer> map) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage querywocoinfenye = stationService.querywocoinfenye(page, limit, map);
        return new ResponseBean(0, querywocoinfenye.getTotal(), querywocoinfenye.getRecords());
    }

    /**
     * 站点密钥查询
     */
    @RequestMapping("/selectPasswodFenye")
    public ResponseBean selectPasswodFenye(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit, @RequestParam Map<String, String> map) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage iPage = stationService.selectPasswodFenye(page, limit, map);
        return new ResponseBean(0, iPage.getTotal(), iPage.getRecords());
    }

    /**
     * 新增站点
     */
    @RequestMapping("/addstation")
    public ResponseBean addstation(Station station, @RequestParam String address) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        //判断站点名称是否重复
        Station panduancf=stationService.selstationName(station);
        if(panduancf!=null){
            return  new ResponseBean(500,null,"站点名称重复，请重新输入");
        }
        int f = stationService.addstastion(station, address);//得到所有传过来的数据添加并且welcome表新增数据
        if (f == -1) {
            return new ResponseBean(400, null, "可用终端不足");
        }
        return new ResponseBean(200, null, null);
    }

    /**
     * 修改站点密码
     * @return
     */
    @PutMapping("/updateStationPwd")
    public ResponseBean updateStationPwd(@RequestBody Map<String,String> map){

        ResponseBean responseBean = ifPassword(map);

        if (responseBean!=null){
            return responseBean;
        }

        boolean update = stationService.updateUserPwd(map);
        if (update==false){
            return new ResponseBean(500,"操作错误","修改失败");
        }

        return new ResponseBean(200,"操作成功","修改成功");
    }

    /**
     * 判断新旧密码是否一致
     * @return
     */
    public ResponseBean ifPassword(Map<String,String> map ){
        String jiupwd=map.get("jiupwd");
        String stationpwd=map.get("stationPassword");
        if (jiupwd.equals(stationpwd)){
            return new ResponseBean(500,"操作错误","旧密码与新密码一致");
        }
        //判断用户名的旧密码是否一致
        boolean b=stationService.selectUserPwd(map);
        if (b==false){

            logger.info("操作错误，旧密码错误");
            return new ResponseBean(500,"操作错误","旧密码错误");
        }
    return null;
    }
    /**
     * 修改站点的信息
     * @param station
     * @param address
     * @return
     */
    @RequestMapping("/editStationMes")
    public ResponseBean editStationMes(Station station, String address,String adminidnow) {
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        //判断站点名字是否重复
        Station s=stationService.findStationName(station);
        if(s!=null){
            return new ResponseBean(500,null,"站点名重复");
        }
        int n=stationService.editStationMes(station,address);
        int code=n>0?200:500;
        return new ResponseBean(code,null,null);
    }



    /**
     * 站点名称，在页面右边名称
     * @param stationid
     * @return
     */
    @GetMapping("stationName")
    public ResponseBean stationName(Integer stationid){

        Station station=stationService.getById(stationid);
        return new ResponseBean(200,"success",station);
    }
    /**
     * 查所有版权授权
     * @param page
     * @param limit
     * @param
     * @return
     */
    @RequestMapping("/selcopyrightstation")
    public ResponseBean selcopyrightstation(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int limit,String search, Integer copyrightid,String token){
        Admin admin = (Admin)request.getSession().getAttribute("admin");
        if (admin==null)
        {
            return new ResponseBean(401, "没有登录", null);
        }
        IPage re=stationService.selcopyrightstation(page,limit,search,copyrightid,token);
        return new ResponseBean(0,re.getTotal(),re.getRecords());
    }

}
